package com.springcloud.market.order.service;

import com.springcloud.market.common.dto.OrderDTO;
import com.springcloud.market.common.entity.Order;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public abstract class OrderService {

    @Autowired
    private OrderTimeoutSender orderTimeoutSender;

    /**
     * 创建订单并发送延迟消息
     */
    public Order createOrder() {
        Integer orderId = 202;          // 模拟生成订单 ID
        Integer productId = 203;        // 模拟商品 ID

        // 发送延迟消息（10 秒后触发超时取消）
        try {
            orderTimeoutSender.sendOrderTimeoutMessage(orderId.toString());
        } catch (Exception e) {
            // 记录日志，但不回滚主业务
            log.error("发送超时消息失败：{}", e.getMessage(), e);
        }

        // 返回订单对象（可扩展状态字段：未支付/已支付等）
        return new Order(orderId, productId);
    }

    @GlobalTransactional(rollbackFor = Exception.class) // 分布式事务
    public abstract String createOrder(OrderDTO dto);
}
//
//import com.springcloud.market.common.dto.OrderDTO;
//import com.springcloud.market.common.entity.Order;
//import com.springcloud.market.order.mapper.OrderMapper;
//import com.springcloud.market.common.feign.StockFeignClient;
//import com.springcloud.market.common.model.R;
//import lombok.RequiredArgsConstructor;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//@Service
//@RequiredArgsConstructor
//public class OrderService {
//
//    private final OrderMapper orderMapper;
//    private final StockFeignClient stockFeignClient;
//
//    @Transactional
//    public String createOrder(OrderDTO dto) {
//        // 1. 扣库存
//        R<Void> r = stockFeignClient.reduceStock(dto.getSkuId(), dto.getNum());
//        if (r.getCode() != 200) {
//            throw new RuntimeException("扣库存失败：" + r.getMsg());
//        }
//
//        // 2. 创建订单
//        Order order = new Order();
//        order.setUserId(dto.getUserId());
//        order.setSkuId(dto.getSkuId());
//        order.setNum(dto.getNum());
//        orderMapper.insert(order);
//
//        return "订单创建成功，订单号：" + order.getId();
//    }
//
//    public Object creatOrder(OrderDTO dto) {
//        return null;
//    }
//}